package cn.yuanqiao.web.controller.archive.sealmanage;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.sealmanage.domain.SealManage;
import cn.yuanqiao.archive.sealmanage.service.ISealmanageService;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.context.ResponseUtils;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;


import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;

import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * 归档章管理Controller
 *
 * @author yuanqiao
 * @date 2023-10-11
 */
@RestController
@RequestMapping("/archive/sealmanage")
public class SealmanageController extends BaseController
{
    @Autowired
    private ISealmanageService SealmanageService;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    /**
     * 查询归档章管理列表
     */
    //@PreAuthorize("@ss.hasPermi('manage:SEALMANAGE:list')")
    @GetMapping("/list")
    public TableDataInfo list(SealManage Sealmanage)
    {
        startPage();
        List<SealManage> list = SealmanageService.selectSealmanageList(Sealmanage);
        return getDataTable(list);
    }

    /**
     * 导出归档章管理列表
     */
    //@PreAuthorize("@ss.hasPermi('manage:SEALMANAGE:export')")
    @Log(title = "归档章管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SealManage Sealmanage)
    {
        List<SealManage> list = SealmanageService.selectSealmanageList(Sealmanage);
        ExcelUtil<SealManage> util = new ExcelUtil<SealManage>(SealManage.class);
        util.exportExcel(response, list, "归档章管理数据");
    }

    @Log(title = "归档章预览")
    @PostMapping("/viewSeal")
    public void viewSeal(@RequestBody SealManage Sealmanage,HttpServletResponse response) throws Exception {
        String path = SealmanageService.viewSeal(Sealmanage);
        response.reset(); // 非常重要
        // 设置 CORS 响应头
        ResponseUtils.defaultResponse(response);
        //在线预览，浏览器支持的文件类型都能打开
        //URL u = new URL("file:///" + path);
        //response.setContentType(u.openConnection().getContentType());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "inline; filename=\"" + "testpdf.pdf"+"\"");
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(path)));
        byte[] buf = new byte[1024];
        int len = 0;
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        System.gc();
        br.close();
        out.close();
        //return success(SealmanageService.viewSeal(Sealmanage));
    }

    @Log(title = "归档章预览")
    @PostMapping("/viewSeal2")
    public void viewSeal2(@RequestParam("id") Long id,HttpServletResponse response) throws Exception {
        SealManage sealManage = SealmanageService.selectSealmanageByID(id.toString());
        String tableStyle = sealManage.getTableStyle();
        JSONArray jsonArray = JSONArray.parseArray(tableStyle);
        sealManage.setTableStyleJson(jsonArray);
        String path = SealmanageService.viewSeal(sealManage);
        response.reset(); // 非常重要
        // 设置 CORS 响应头
        ResponseUtils.defaultResponse(response);
        //在线预览，浏览器支持的文件类型都能打开
        //URL u = new URL("file:///" + path);
        //response.setContentType(u.openConnection().getContentType());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "inline; filename=\"" + "testpdf.pdf"+"\"");
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(path)));
        byte[] buf = new byte[1024];
        int len = 0;
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        System.gc();
        br.close();
        out.close();
        //return success(SealmanageService.viewSeal(Sealmanage));
    }

    /**
     * 获取归档章管理详细信息
     */
    //@PreAuthorize("@ss.hasPermi('manage:SEALMANAGE:query')")
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") String ID)
    {
        return success(SealmanageService.selectSealmanageByID(ID));
    }

    @GetMapping("/getImagePath")
    public R<String> getImagePath(@RequestParam("id")Long id,@RequestParam("map")String map)
    {
        String path = SealmanageService.getImagePath(id,map);
        return R.ok(path);
    }

    /**
     * 新增归档章管理
     */
    //@PreAuthorize("@ss.hasPermi('manage:SEALMANAGE:add')")
    @Log(title = "归档章管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SealManage Sealmanage)
    {
        return toAjax(SealmanageService.insertSealmanage(Sealmanage));
    }

    /**
     * 修改归档章管理
     */
    //@PreAuthorize("@ss.hasPermi('manage:SEALMANAGE:edit')")
    @Log(title = "归档章管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SealManage Sealmanage)
    {
        return toAjax(SealmanageService.updateSealmanage(Sealmanage));
    }

    /**
     * 删除归档章管理
     */
    //@PreAuthorize("@ss.hasPermi('manage:SEALMANAGE:remove')")
    @Log(title = "归档章管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable String[] IDs)
    {
        return toAjax(SealmanageService.deleteSealmanageByIDs(IDs));
    }

    @Log(title = "归档章管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteTempFile")
    public void deleteTempFile()
    {
        String guidang_position = sysConfigService.selectConfigByKey("SEAL_POSITION");
        if(!StringUtils.isEmpty(guidang_position) && !"null".equals(guidang_position)){
            Long userId = SecurityUtils.getUserId();
            String pdfPath = guidang_position+File.separator+"testpdfwater_"+userId+".pdf";
            File file = new File(pdfPath);
            if(file.exists()){
                file.delete();
            }
            String path = guidang_position+File.separator+"viewSeal_"+userId+".png";
            File file1 = new File(path);
            if(file1.exists()){
                file1.delete();
            }
        }
    }

}
